<template>
  <div id="app">
    <div class="container">
      <!-- 页头 -->
      <div class="nav-bar">
        <div class="nav-title">航道尺度</div>
      </div>
      <div class="change_type">
        <div class="change_type_btn" @click="searchMonthScale">查看月度计划</div>
        <div class="change_type_btn" @click="handleChangeType">切换成{{ type=='1'?'图表':'表格' }}</div>
      </div>
      <div v-show="type ==='0'" class="variable-width-bar-chart">
        <div ref="chart" :style="{ width: '100vw', height: '90vh' }" />
      </div>
      <div v-show="type ==='1'" class="channel-table-container">
        <!-- 标题区域 -->
        <div class="table-header">
          <div class="main-title">{{ title1 }}</div>
          <div class="date-range">{{ title2 }}</div>
        </div>

        <!-- 表格区域 -->
        <div class="table-wrapper">
          <table>
            <thead>
              <tr>
                <th rowspan="2" class="waterway-header">航道名称/航道起讫点</th>
                <th rowspan="2" class="main-scale">周维护尺度<br>(水深×宽度)</th>
                <th colspan="4" class="feature-header">主要特征水道</th>
              </tr>
              <tr>
                <th class="waterway-name">水道</th>
                <th class="waterway-scale">周维护尺度</th>
                <th colspan="2" class="reference-header">参考水位</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="(group, groupIndex) in groupedData">
                <tr v-for="(item, index) in group.items" :key="`${groupIndex}-${index}`">
                  <!-- 航道名称列（只显示在第一行） -->
                  <td v-if="index === 0" :rowspan="group.items.length" class="waterway-name-cell">
                    {{ group.name }}
                  </td>

                  <!-- 航道维护尺度列（只显示在第一行） -->
                  <td v-if="index === 0" :rowspan="group.items.length" class="main-scale-cell">
                    <div v-html="formatScale(group.mainScale)" />
                  </td>

                  <!-- 水道数据列 -->
                  <td class="feature-cell">{{ item.zytzSd }}</td>
                  <td class="scale-cell">{{ item.zytzZwhcd }}</td>
                  <td class="station-cell">{{ item.ckswSwz }}</td>
                  <td class="water-level-cell">{{ item.ckswSw }}</td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { pushShowScaleAll, pushShowScale } from '@/api/mobile/index'
import echarts from 'echarts'

export default {
  name: 'Scale',
  data: function() {
    return {
      userId: null,
      sites: [],
      activeSite: 0,
      chart: null,
      type: '0', // 0：图表 1:表格
      title1: '',
      title2: '',
      chartInstance: null

    }
  },
  computed: {
    // 将数据按航道名称分组
    groupedData() {
      const groups = {}
      this.sites.forEach(item => {
        if (!groups[item.detailName]) {
          groups[item.detailName] = {
            name: item.detailName,
            mainScale: item.ssKd, // 航道维护尺度
            items: []
          }
        }
        groups[item.detailName].items.push(item)
      })
      return Object.values(groups)
    }
  },
  async mounted() {
    // 从 URL 获取 code
    const urlParams = new URLSearchParams(window.location.search)
    const userId = urlParams.get('userId')

    if (userId) {
      this.userId = userId
    }
    // 初始化页面数据
    this.parseUrlParams()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
  },
  methods: {
    // 格式化尺度数据，将换行符转换为<br>标签
    formatScale(scale) {
      if (!scale) return ''
      return scale.replace(/\n/g, '<br>')
    },
    handleChangeType() {
      this.type = this.type === '1' ? '0' : '1'
      this.parseUrlParams()
    },
    searchMonthScale() {
      const currentUrl = encodeURIComponent(window.location.href) // 记录当前完整路径
      this.$router.push({
        path: '/scaleMonth',
        query: { from: currentUrl } // 携带来源地址
      })
    },
    // 解析URL参数
    async parseUrlParams() {
      // 获取查询参数
      const queryString = window.location.search
      this.queryParams = queryString

      // 解析查询参数
      const params = new URLSearchParams(queryString)

      if (params.has('messageId')) {
        const messageId = params.get('messageId')
        const res = await pushShowScale({ userId: this.userId, messageId, type: this.type, yearWeek: '202523' })
        this.sites = res.data
        this.title1 = res.title1
        this.title2 = res.title2
      } else {
        const res = await pushShowScaleAll({ type: this.type })
        this.sites = res.data
        this.title1 = res.title1
        this.title2 = res.title2
      }
      if (this.type === '0') {
        this.initChart()
        window.addEventListener('resize', this.resizeChart)
      }
    },
    initChart() {
      if (!this.chartInstance) {
        this.chartInstance = echarts.init(this.$refs.chart)
        this.updateChart()
      }
    },
    updateChart() {
      if (!this.chartInstance || !this.sites.length) return

      // 处理数据：转换为数值类型
      const data = this.sites.map(item => ({
        ...item,
        ss: parseFloat(item.ss),
        kd: parseFloat(item.kd)
      })).reverse()

      // 计算柱子的起始位置（垂直方向）
      let currentPosition = 0
      const gap = 15 // 柱子之间的间隔
      const processedData = data.map((item, index) => {
        const start = currentPosition
        currentPosition += item.kd + gap
        return {
          ...item,
          start,
          end: start + item.kd
        }
      })

      // 计算最大高度用于X轴（原Y轴）
      const maxHeight = Math.max(...data.map(item => item.ss)) * 1.2

      const option = {
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(50,50,50,0.9)',
          borderColor: '#333',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            const item = params.data.rawData
            if (!item) return
            return `
                <div style="margin-bottom:5px;font-weight:bold">${item.detailName}</div>
                <div>尺度: <span style="color:#ffd700;font-weight:bold">${item.ss}米</span></div>
                <div>宽度: <span style="color:#ffd700;font-weight:bold">${item.kd}米</span></div>
                <div>${item.dataRange}</div>
                ${item.other ? `<div style="width:200px;word-wrap:break-word;overflow:visible;white-space:normal;">${item.other}</div>` : ''}
              `
          }
        },
        grid: {
          top: 60, // 增加顶部空间（原为40）
          bottom: 30,
          left: 80,
          right: 30
        },
        // 添加图例配置
        legend: {
          // orient: 'vertical',
          show: true,
          data: ['水深'],
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          itemStyle: {
            color: '#85bedb' // 设置图例颜色
          }
        },
        yAxis: {
          type: 'value',
          name: '',
          nameLocation: 'middle',
          nameGap: 30,
          min: 0,
          max: currentPosition,
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        xAxis: {
          type: 'value',
          name: '',
          min: 0,
          max: maxHeight,
          position: 'top', // 关键修改：将刻度移到顶部
          axisLine: {
            lineStyle: {
              // type: 'dashed',
              color: '#666'
            },
            onZero: false
          },
          // axisTick: {
          //   show: true,
          //   alignWithLabel: true
          // },
          splitLine: {
            show: false
          },
          inverse: true // 关键修改：取消逆序
        },
        series: [{
          type: 'custom',
          name: '水深', // 添加系列名称，与图例对应
          renderItem: (params, api) => {
            const dataIndex = params.dataIndex
            const item = processedData[dataIndex]

            // 旋转坐标：交换X和Y轴
            const startPoint = api.coord([0, item.start])
            const endPoint = api.coord([item.ss, item.end])

            // 绘制垂直柱状图
            return {
              type: 'rect',
              shape: {
                x: startPoint[0],
                y: startPoint[1],
                width: endPoint[0] - startPoint[0],
                height: endPoint[1] - startPoint[1]
              },
              style: {
                fill: '#85bedb',
                shadowColor: 'rgba(0,0,0,0.2)',
                shadowBlur: 3,
                shadowOffsetY: 2
              },
              emphasis: {
                style: {
                  shadowBlur: 8,
                  shadowColor: 'rgba(0,0,0,0.3)'
                }
              }
            }
          },
          encode: {
            y: [1, 2],
            x: 0
          },
          data: processedData.map(item => ({
            value: [item.ss, item.start, item.end],
            rawData: item
          }))
        },
        // 新增文本系列
        {
          type: 'custom',
          name: '航道名称',
          renderItem: (params, api) => {
            const dataIndex = params.dataIndex
            const item = processedData[dataIndex]

            // 计算柱子中心位置
            const centerY = (item.start + item.end) / 2

            // 获取柱子顶部坐标
            const topPoint = api.coord([0, centerY])

            return {
              type: 'text',
              position: [topPoint[0] - 80, topPoint[1] + 8], // 在柱子上方显示
              style: {
                text: item.detailName,
                fill: 'gray',
                fontSize: 12,
                fontWeight: 'bold',
                textAlign: 'center',
                textVerticalAlign: 'bottom'
              },
              zlevel: 10 // 确保文本在柱子上面
            }
          },
          data: processedData // 使用相同的数据源
        }]
      }

      this.chartInstance.setOption(option)
    },
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    }
  }
}
</script>
<style scoped>
.channel-table-container {
  font-family: "Microsoft YaHei", sans-serif;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 16px;
}

.table-header {
  padding: 16px;
  text-align: center;
  background: #f0f7ff;
  border-bottom: 1px solid #e8e8e8;
}

.main-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  line-height: 1.5;
}

.date-range {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.publisher {
  font-size: 14px;
  color: #666;
  margin-top: 8px;
}

.unit {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
  font-weight: bold;
}

.table-wrapper {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  min-width: 800px;
}

th, td {
  border: 1px solid #e8e8e8;
  padding: 12px 8px;
  text-align: center;
  vertical-align: middle;
}

th {
  background: #f0f7ff;
  font-weight: bold;
  color: #333;
}

.waterway-header {
  width: 25%;
}

.main-scale {
  width: 20%;
}

.feature-header {
  width: 55%;
}

.waterway-name {
  width: 20%;
}

.waterway-scale {
  width: 15%;
}

.reference-header {
  width: 20%;
}

.waterway-name-cell {
  background: #f9f9f9;
  font-weight: bold;
}

.main-scale-cell {
  background: #f9f9f9;
}

.feature-cell {
  color: #1890ff;
}

.station-cell {
  background: #f0f7ff;
}

.water-level-cell {
  background: #e6f7ff;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .channel-table-container {
    margin: 8px;
  }

  .table-header {
    padding: 12px;
  }

  .main-title {
    font-size: 16px;
  }

  th, td {
    padding: 8px 4px;
    font-size: 12px;
  }
}
.change_type{
  display: flex;
  align-items: center;
  justify-content: end;
  margin-top: 20px;
  padding-right: 20px;
}
.change_type_btn{
  display: flex;
    align-items: center;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 20px;
    font-size: 0.9rem;
    cursor: pointer;
    transition: all 0.3s;
    height: 35px;
    background: #1a2980;
    margin-left: 10px;
}
.legend-rotate {
    transform: rotate(-45deg); /* 旋转角度 */
    transform-origin: center; /* 旋转中心 */
}
#app {
  max-width: 1200px;
  margin: 0 auto;
}

/* 页头样式 */

/* 导航栏 */
.nav-bar {
  background: rgb(26, 41, 128) !important;
  color: white;
  padding: 16px;
  display: flex;
  align-items: center;
  position: relative;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
}

.title {
  font-size: 2.2rem;
  margin-bottom: 10px;
  background: linear-gradient(to right, #3498db, #1abc9c);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.subtitle {
  color: #bdc3c7;
  font-size: 1.1rem;
  max-width: 600px;
  margin: 0 auto;
}

.chart-container {
  background: rgba(255, 255, 255, 0.08);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  height: 500px;
}

#mainChart {
  width: 100vw;
  height: 100vh;
}

.info-box {
  position: absolute;
  top: 20px;
  left: 20px;
  background: rgba(30, 30, 40, 0.85);
  border: 2px solid #3498db;
  border-radius: 10px;
  padding: 15px;
  width: 200px;
  z-index: 10;
}

.info-title {
  color: #3498db;
  text-align: center;
  font-size: 1.2rem;
  margin-bottom: 10px;
  font-weight: bold;
}

.info-item {
  margin-bottom: 8px;
  font-size: 0.9rem;
}

.info-label {
  color: #bdc3c7;
}

.info-value {
  color: #1abc9c;
  font-weight: bold;
}

.depth-markers {
  position: absolute;
  right: 20px;
  top: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  z-index: 5;
  pointer-events: none;
}

.depth-marker {
  color: #ecf0f1;
  font-size: 1rem;
  font-weight: bold;
  background: rgba(0, 0, 0, 0.4);
  padding: 5px 10px;
  border-radius: 5px;
}

.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.site-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  margin: 20px 0;
  padding: 15px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 15px;
}

.site-tag {
  padding: 8px 16px;
  background: rgba(52, 152, 219, 0.3);
  border-radius: 20px;
  font-size: 0.95rem;
  color: #ecf0f1;
  cursor: pointer;
  transition: all 0.3s ease;
}

.site-tag.active {
  background: rgba(26, 188, 156, 0.6);
  font-weight: bold;
}

.legend {
  display: flex;
  justify-content: center;
  gap: 25px;
  margin: 20px 0;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 18px;
  height: 18px;
  border-radius: 4px;
}

.legend-safe {
  background: linear-gradient(to right, #3498db, #1abc9c);
}

.legend-warning {
  background: linear-gradient(to right, #f39c12, #e67e22);
}

.legend-danger {
  background: linear-gradient(to right, #e74c3c, #c0392b);
}

.width-indicator {
  text-align: center;
  padding: 15px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  margin: 20px 0;
  color: #bdc3c7;
  font-size: 0.95rem;
}

.footer {
  text-align: center;
  padding: 20px 0;
  margin-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  color: #7f8c8d;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .title {
      font-size: 1.8rem;
  }

  .chart-container {
      height: 450px;
  }

  .controls {
      flex-direction: column;
      align-items: center;
  }

  .info-box {
      width: 180px;
      padding: 12px;
  }
}
</style>
